package org.bronycorps.mlptss.domain.actor;

import org.bronycorps.mlptss.domain.controller.AbstractController;
import org.bronycorps.mlptss.domain.controller.MissileController;
import org.bronycorps.mlptss.domain.layer.MissileLayer;
import org.bronycorps.mlptss.domain.layer.Track;
import org.bronycorps.mlptss.domain.model.AbstractActorModel;
import org.bronycorps.mlptss.domain.model.event.StateChangeEvent;
import org.bronycorps.mlptss.domain.model.event.StateChangeEventListener;
import org.bronycorps.mlptss.utils.DrawableAnimation;

import com.badlogic.gdx.math.Vector2;

public class MissileActor extends AbstractActor implements
		StateChangeEventListener {

	private DrawableAnimation defaultAnimation;
	private final MissileController missileController;
	private final Track track;

	public MissileActor(MissileController controller, Track track) {
		super();
		this.missileController = controller;
		this.track = track;

		this.missileController.getModel().addListener(this);

		createAnimation();
		this.currentAnimation = this.defaultAnimation;

		setDrawable(this.currentAnimation.getDrawableKeyFrame(this.currentTime));
		setWidth(getPrefWidth());
		setHeight(getPrefHeight());
		setOrigin(getModelOrigin().x, getModelOrigin().y);

		this.hitBox.setWidth(getBounds().width);
		this.hitBox.setHeight(getBounds().height);
	}

	@Override
	public void act(float delta) {
		super.act(delta);

		setRotation(this.missileController.getModel().getAngle());
	}

	private void createAnimation() {
		this.defaultAnimation = this.missileController.getModel()
				.getDefaultAnimation();
	}

	@Override
	protected AbstractController getController() {
		return this.missileController;
	}

	public DrawableAnimation getDefaultAnimation() {
		return this.defaultAnimation;
	}

	public MissileController getMissile() {
		return this.missileController;
	}

	@Override
	public AbstractActorModel getModel() {
		return this.missileController.getModel();
	}

	@Override
	protected Vector2 getModelPosition() {
		return getModel().getPosition();
	}

	@Override
	public Track getTrack() {
		return this.track;
	}

	@Override
	public void onStateChange(StateChangeEvent event) {
		switch (event.getMissile().getState()) {
		case EXPLODE:
			// when exploding, the entity must not move anymore
			// TrajectFactory.getInstance().clearTweens(this);
			// switch to explosion animation
			// switchAnimation(this.explodeAnimation);
			terminate();
			break;
		default:
			switchAnimation(getDefaultAnimation());
			break;
		}
	}

	public void setInitialPosition(float x, float y) {
		getModelPosition().set(x, y);
		updateVisualPosition();
	}

	public void setInitialPosition(Vector2 position) {
		getModelPosition().set(position);
		updateVisualPosition();
	}

	public void terminate() {
		((MissileLayer) getParent()).removeMissile(this);
	}

}
